package com.example.hello.client.ListBox;

import com.example.hello.ListBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.communication.RpcProxy;
import com.vaadin.client.communication.StateChangeEvent;
import com.vaadin.client.ui.AbstractComponentConnector;
import com.vaadin.shared.ui.Connect;

import java.util.List;

@Connect(ListBox.class)
public class ListBoxConnector extends AbstractComponentConnector implements ChangeHandler {

    ListBoxServerRpc rpc = RpcProxy.create(ListBoxServerRpc.class, this);

    public ListBoxConnector() {
        getWidget().addChangeHandler(this);
    }

    @Override
    protected Widget createWidget() {
        return GWT.create(VListBox.class);
    }

    @Override
    public ListBoxState getState() {
        return (ListBoxState) super.getState();
    }

    @Override
    public VListBox getWidget() {
        return (VListBox) super.getWidget();
    }

    @Override
    public void onStateChanged(StateChangeEvent stateChangeEvent) {
        super.onStateChanged(stateChangeEvent);

        ListBoxState state = getState();

        VListBox listBox = getWidget();

        List<String> items = state.getItems();
        List<Boolean> selected = state.getSelected();
        List<String> values = state.getValues();

        listBox.clear();

        for (int i = 0; i < state.getItems().size(); i++) {
            listBox.addItem(items.get(i));
            listBox.setItemSelected(i, selected.get(i));
            listBox.setValue(i, values.get(i));
        }
        listBox.setMultipleSelect(getState().isMultipleSelect());
        listBox.setVisibleItemCount(getState().getVisibleItems());
    }

    @Override
    public void onChange(ChangeEvent event) {
        rpc.sendSelected(getWidget().getItemText(getWidget().getSelectedIndex()));
    }
}